package leetcode

import "math"

// Definition for a binary tree node.
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

// https://leetcode.com/problems/find-largest-value-in-each-tree-row/
func LargestValues(root *TreeNode) []int {
	nodes, res := make([]*TreeNode, 1), make([]int, 0)
	if root == nil {
		return res
	}
	nodes[0] = root
	traversal(nodes, &res)
	return res
}

func traversal(levelNodes []*TreeNode, res *[]int) {
	if len(levelNodes) == 0 {
		return
	}
	nextLevel := make([]*TreeNode, 0)
	largest := math.MinInt
	for _, v := range levelNodes {
		if largest < v.Val {
			largest = v.Val
		}
		if v.Left != nil {
			nextLevel = append(nextLevel, v.Left)
		}
		if v.Right != nil {
			nextLevel = append(nextLevel, v.Right)
		}
	}
	*res = append(*res, largest)
	traversal(nextLevel, res)
}
